package demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import demo.domain.User;
import demo.service.UserService;

@RestController
public class HelloController {

    @Autowired
    private UserService userService;

    /**
     * Return hello world when requesting server root
     * 
     * @return String
     */
    @RequestMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
    public String root() {
        return "hello world";
    }

    /**
     * Return the number of users when requesting /number
     * 
     * @return String
     */
    @RequestMapping("/number")
    public String number() {
        final long nb = userService.countUsers();
        final StringBuffer vSb = new StringBuffer("Number of users : ");
        vSb.append(nb);
        return vSb.toString();
    }

    /**
     * Return the list of users when requesting /greeting
     * 
     * @return String
     */
    @RequestMapping("/greeting")
    public String greeting() {
        final List<User> vUsers = userService.findAllUsers();
        final StringBuffer vSb = new StringBuffer("List of users :");

        for (final User vUser : vUsers) {
            vSb.append(vUser.getLastName()).append(" ").append(vUser.getFirstName()).append("");
        }

        return vSb.toString();
    }

    @RequestMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
    public List<User> users() {
        return userService.findAllUsers();
    }

    @RequestMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE)
    public User getUserByLogin(@RequestParam final String login) {
        return userService.findByLogin(login);
    }

}
